package controllers

import (
	"bsm/logger"
	"bsm/models"
	"bsm/services"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type SystemController interface {
	GetRoles(c *gin.Context)
	GenerateUserId(c *gin.Context)
	GetUsers(c *gin.Context)
	GetSystemStats(c *gin.Context)
	GetSessions(c *gin.Context)
	GetProjects(c *gin.Context)
	TerminateSession(c *gin.Context)
	TerminateUserSessions(c *gin.Context)

	AddUser(c *gin.Context)
	ResetPassword(c *gin.Context)
	FreezeUser(c *gin.Context)
	UnfreezeUser(c *gin.Context)
}

type SystemControllerImpl struct {
	systemService services.SystemService
	userService   services.UserService
	svcAuth       services.AuthService
}

func NewSystemController(systemService services.SystemService, userService services.UserService, svcAuth services.AuthService) SystemController {
	return &SystemControllerImpl{
		systemService: systemService,
		userService:   userService,
		svcAuth:       svcAuth,
	}
}

func (sc *SystemControllerImpl) GetRoles(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	roles, err := sc.userService.GetRoles()
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "System-GetRoles",
		}).Errorf("获取角色列表失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"信息": "获取角色列表失败: "})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": roles,
	})
}

func (sc *SystemControllerImpl) GenerateUserId(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	username := c.Query("new_name")
	if username == "" {
		c.JSON(http.StatusBadRequest, gin.H{"信息": "用户名不能为空"})
		return
	}

	userID, err := sc.userService.GenerateUserId(username)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "System-GenerateUserId",
		}).Errorf("生成用户ID失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"信息": "生成用户ID失败: "})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": userID,
	})
}

// GetUsers 获取用户列表
func (sc *SystemControllerImpl) GetUsers(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
	keyword := c.Query("keyword")

	users, total, err := sc.systemService.GetUsersWithPagination(page, limit, keyword)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "System-GetUsers",
		}).Errorf("获取用户列表失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"信息": "获取用户列表失败: "})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":  0,
		"msg":   "success",
		"count": total,
		"data":  users,
	})
}

// DeleteUser 删除用户
func (sc *SystemControllerImpl) DeleteUser(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	userID := c.Param("user_id")
	if userID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"信息": "无效的用户ID"})
		return
	}

	if err := sc.userService.DeleteUser(userID); err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "System-DeleteUser",
			"user_id":   userID,
		}).Errorf("删除用户失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"信息": "删除用户失败 "})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "用户删除成功",
	})
}

// GetSystemStats 获取系统统计
func (sc *SystemControllerImpl) GetSystemStats(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	stats, err := sc.systemService.GetSystemStats()
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "System-GetSystemStats",
		}).Errorf("获取统计信息失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"信息": "获取统计信息失败 "})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": stats,
	})
}

// GetSessions 获取会话列表
func (sc *SystemControllerImpl) GetSessions(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	// 支持按用户账号筛选
	userID := c.Query("user_id")
	if userID != "" {

		sessions, err := sc.systemService.GetUserSessions(userID)
		if err != nil {
			logger.WithFields(map[string]interface{}{
				"layer":     "controller",
				"operation": "System-GetSessions",
				"user_id":   userID,
			}).Errorf("获取会话列表失败: %v", err)
			c.JSON(http.StatusInternalServerError, gin.H{"信息": "获取会话列表失败 "})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "success",
			"data": sessions,
		})
		return
	}

	// 获取所有会话
	sessions, err := sc.systemService.GetAllSessions()
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "System-GetSessions",
		}).Errorf("获取会话列表失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"信息": "获取会话列表失败 "})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": sessions,
	})
}

// TerminateSession 终止会话
func (sc *SystemControllerImpl) TerminateSession(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	sessionID := c.Param("session_id")

	if err := sc.systemService.TerminateSession(sessionID); err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":      "controller",
			"operation":  "System-TerminateSession",
			"session_id": sessionID,
		}).Errorf("终止会话失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"信息": "终止会话失败 "})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "会话终止成功",
	})
}

// TerminateUserSessions 终止用户的所有会话
func (sc *SystemControllerImpl) TerminateUserSessions(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	userID := c.Param("user_id")

	terminated, err := sc.systemService.TerminateUserSessions(userID)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "System-TerminateUserSessions",
			"user_id":   userID,
		}).Errorf("终止会话失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"信息": "终止会话失败 "})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "会话终止成功",
		"data": gin.H{"terminated_count": terminated},
	})
}

func (sc *SystemControllerImpl) GetProjects(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	orgCode := c.Query("org_code")

	dType := c.Query("design_type")
	designType, err := strconv.Atoi(dType)
	if err != nil {
		designType = models.DesignType_All
	}

	projects, err := sc.systemService.GetProjects(orgCode, designType)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "System-GetProjects",
		}).Errorf("获取项目列表失败: %v", err)
		c.JSON(http.StatusInternalServerError, models.ResponseModel{
			Code:  500,
			Count: 0,
			Msg:   "获取项目列表失败",
		})
		return
	}

	c.JSON(http.StatusOK, models.ResponseModel{
		Code:  0,
		Msg:   "success",
		Count: len(projects),
		Data:  projects,
	})
}

func (sc *SystemControllerImpl) AddUser(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	// 解析请求体
	type AddUserRequest struct {
		User  models.ProjectUser `json:"user"`
		Roles []string           `json:"roles"`
	}

	var req AddUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"信息": "请求体格式错误"})
		return
	}

	user, _ := sc.userService.GetUserProfile(req.User.UserID)
	// 检查用户是否已存在
	if user != nil {
		c.JSON(http.StatusBadRequest, models.ResponseModel{
			Code:  400,
			Count: 0,
			Msg:   "用户已存在",
		})
		return
	}

	// 验证用户名
	if req.User.UserName == "" {
		c.JSON(http.StatusBadRequest, gin.H{"信息": "用户名不能为空"})
		return
	}
	// 验证角色
	if len(req.Roles) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"信息": "角色不能为空"})
		return
	}
	// 验证组织代码
	if req.User.OrgCode == "" {
		c.JSON(http.StatusBadRequest, gin.H{"信息": "组织代码不能为空"})
		return
	}

	var err error
	if req.User.Password == "" {
		err = sc.userService.UpdateUser(req.User, req.Roles)
	} else {
		err = sc.userService.AddUser(req.User, req.Roles)
	}
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "System-AddUser",
		}).Errorf("添加用户失败: %v", err)
		c.JSON(http.StatusInternalServerError, models.ResponseModel{
			Code:  500,
			Count: 0,
			Msg:   "添加用户失败",
		})
		return
	}

	c.JSON(http.StatusOK, models.ResponseModel{
		Code:  0,
		Msg:   "success",
		Count: 1,
	})
}

func (sc *SystemControllerImpl) ResetPassword(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	// 解析请求体
	type ResetPasswordRequest struct {
		UserID string `json:"user_id"`
	}

	var req ResetPasswordRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"信息": "请求体格式错误"})
		return
	}

	// 检查用户是否存在
	user, _ := sc.userService.GetUserProfile(req.UserID)
	if user == nil {
		c.JSON(http.StatusBadRequest, models.ResponseModel{
			Code:  400,
			Count: 0,
			Msg:   "用户不存在",
		})
		return
	}

	// 重置密码
	err := sc.userService.ResetPassword(req.UserID)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "System-ResetPassword",
			"user_id":   req.UserID,
		}).Errorf("重置密码失败: %v", err)
		c.JSON(http.StatusInternalServerError, models.ResponseModel{
			Code:  500,
			Count: 0,
			Msg:   "重置密码失败",
		})
		return
	}

	c.JSON(http.StatusOK, models.ResponseModel{
		Code:  0,
		Msg:   "success",
		Count: 1,
	})
}

func (sc *SystemControllerImpl) FreezeUser(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	// 解析请求体
	type FreezeUserRequest struct {
		UserID string `json:"user_id"`
	}

	var req FreezeUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"信息": "请求体格式错误"})
		return
	}

	// 检查用户是否存在
	user, _ := sc.userService.GetUserProfile(req.UserID)
	if user == nil {
		c.JSON(http.StatusBadRequest, models.ResponseModel{
			Code:  400,
			Count: 0,
			Msg:   "用户不存在",
		})
		return
	}

	// 冻结用户
	err := sc.userService.FreezeUser(req.UserID)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "System-FreezeUser",
			"user_id":   req.UserID,
		}).Errorf("冻结用户失败: %v", err)
		c.JSON(http.StatusInternalServerError, models.ResponseModel{
			Code:  500,
			Count: 0,
			Msg:   "冻结用户失败",
		})
		return
	}

	c.JSON(http.StatusOK, models.ResponseModel{
		Code:  0,
		Msg:   "success",
		Count: 1,
	})
}

func (sc *SystemControllerImpl) UnfreezeUser(c *gin.Context) {
	// 验证用户信息
	if !sc.svcAuth.JWTAuthUser(c) {
		return
	}

	// 解析请求体
	type UnfreezeUserRequest struct {
		UserID string `json:"user_id"`
	}

	var req UnfreezeUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"信息": "请求体格式错误"})
		return
	}

	// 检查用户是否存在
	user, _ := sc.userService.GetUserProfile(req.UserID)
	if user == nil {
		c.JSON(http.StatusBadRequest, models.ResponseModel{
			Code:  400,
			Count: 0,
			Msg:   "用户不存在",
		})
		return
	}

	// 解冻用户
	err := sc.userService.UnfreezeUser(req.UserID)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "controller",
			"operation": "System-UnfreezeUser",
			"user_id":   req.UserID,
		}).Errorf("解冻用户失败: %v", err)
		c.JSON(http.StatusInternalServerError, models.ResponseModel{
			Code:  500,
			Count: 0,
			Msg:   "解冻用户失败",
		})
		return
	}

	c.JSON(http.StatusOK, models.ResponseModel{
		Code:  0,
		Msg:   "success",
		Count: 1,
	})
}
